/**
 * Copyright (c) 2018-present, Chen Guodong
 * All rights reserved.
 *
 * @flow
 */


<template>
  <div class="content">
    <!-- map -->
    <div id="map-content"></div>
    <i class="iconfont icon-fanhui backBtn" @click="gotoScreen"></i>
    <MapLayer></MapLayer>
    <div class="header">
      <!-- <div class="title">伍家岗房屋征收数据管理中心</div> -->
      <div class="title">
        {{screenProject.title}}
        <span
          class="curStatus"
          @click="showTimeLine"
          v-if="projectStatus === 'IN_PROGRESS'"
          style="color: #00b7e5"
        >
          <i class="iconfont icon-jinhangzhong1" style="color: #00b7e5"></i>
          {{projectStatus | getCN}}
        </span>
        <span
          class="curStatus"
          @click="showTimeLine"
          v-if="projectStatus === 'COMPLETED'"
          style="color: #2b821d"
        >
          <i class="iconfont icon-icon-" style="color: #2b821d"></i>
          {{projectStatus | getCN}}
        </span>
        <span
          class="curStatus"
          @click="showTimeLine"
          v-if="projectStatus === 'PLAN'"
          style="color: #ffff66"
        >
          <i class="iconfont icon-jihua1" style="color: #ffff66"></i>
          {{projectStatus | getCN}}
        </span>
      </div>
      <div class="types">
        <SignStatus
          :onePageVis="onePageVis"
          ref="signStatus"
          :onePageData="onePageData"
          :signStatusData="signStatusData"
        ></SignStatus>
      </div>
      <MapLegend
        :legendData="legendData"
        :unselectedStatus="unselectedStatus"
        :handlerMapLegend="handlerMapLegend"
        :onePageVis="onePageVis"
      ></MapLegend>
    </div>
    <SearchContent
      :onePageVis="onePageVis"
      :allData="allData"
      :handlerSearchItem="handlerSearchItem"
    ></SearchContent>
    <PageOne :onePageVis="onePageVis" :onePageData="onePageData" :priceofavg="priceofavg"></PageOne>
    <PageTwo :onePageVis="onePageVis"></PageTwo>
    <div :class="['btns', onePageVis ? 'btnShow' : 'btnHide']">
      <el-button icon="el-icon-arrow-right" type="primary" circle class="btn" @click="changePage"></el-button>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { lazyAMapApiLoaderInstance } from "vue-amap";
import {
  reqMapInfo,
  reqProjectInit,
  reqAll,
  reqSignStatus
} from "../../api/index.js";
import { showMessage } from "../../utils/index.js";
import { index_by_status, statusColor } from "../../utils/contact.js";
import config from "../../utils/config.js";
import PageOne from "./PageOne";
// import PageTwo from "./PageTwo";
import SignStatus from "./SignStatus";
import SearchContent from "./SearchContent";
import MapLegend from "../../components/MapLegend";
import MapLayer from './MapLayer';

const PageTwo = Vue.component("later", function(resolve) {
  setTimeout(function() {
    require(["./PageTwo"], resolve);
  }, 1000);
});

// import {}

export default {
  data() {
    return {
      screenProject: {}, //当前项目信息
      contract_status: 0,
      onePageVis: true,
      onePageData: {}, //onepageData数据
      priceofavg: 0, //均价
      title: "",
      allInfo: "", //项目初始化的所有信息
      allData: [], //所有项目的列表信息
      // allMarks: [], //画地图中的所有点位信息
      projectInfo: {},
      pointers: {},
      animatePointers: {},
      unselectedStatus: [], //表示legend未选中的status, 空表示全部选中
      legendData: [],
      projectStatus: "", //项目状态
      signStatusData: [],
      // redPolygon: {},
      mapLayers:{}, //图层对象集
    };
  },
  watch: {
    unselectedStatus: function(data) {
      let hideSeqno = [];
      let pointerVis = {};
      const self = this;
      const uns = this.unselectedStatus;
      const allData = this.allData;
      for (let i = 0; i < allData.length; i++) {
        if (uns.indexOf(allData[i].status) != -1) {
          pointerVis[allData[i].serialno] = false;
        } else {
          pointerVis[allData[i].serialno] = true;
        }
      }
      for (let j in pointerVis) {
        if (self.pointers[j]) {
          if (pointerVis[j]) {
            self.pointers[j].show();
          } else {
            self.pointers[j].hide();
          }
        }
        if (self.animatePointers[j]) {
          if (pointerVis[j]) {
            self.animatePointers[j].show();
          } else {
            self.animatePointers[j].hide();
          }
        }
      }
    }
  },
  methods: {
    // 向后台获取数据
    async reqScreenData() {
      const self = this;
      const data = await reqProjectInit({
        seqno: self.$router.history.current.query.seqno
      });
      if (data.code === 1) {
        self.screenProject = data.data.item;
        self.priceofavg = data.data.priceofavg;
        self.allData = data.data.allItemInfo;
        self.title = data.data.title;
        self.legendData = data.data.legendData;
        self.onePageData = data.data.pandect;
        self.projectStatus = data.data.status;
        // pageTypes
        self.createMarks();
        self.createAreaWall();
      } else {
        showMessage(self, "地图数据加载失败", "warning", "警告");
      }
    },
    // 初始化地图
    async initMap() {
      const self = this;
      self.mapObj = new AMap.Map("map-content", {
        mapStyle: "amap://styles/23a66b23dd15eaef820fe04440968168", //设置地图的显示样式
        // viewMode: "3D",
        showBuildingBlock: true,
        expandZoomRange: true,
        buildingAnimation: true,
        // pitch: 60,
        zoom: 13.5,
        zooms: [3, 18],
        center: [111.387972, 30.629671],
        zIndex: 1,
        layers: [
          new AMap.TileLayer({
            zIndex: 1,
            opacity: 1,
            getTileUrl:
              "http://t{1,2,3,4}.tianditu.gov.cn/DataServer?T=img_w&x=[x]&y=[y]&l=[z]"
          }),
        ]
      });
      //区域高清瓦片定义
      self.mapLayers['HDVLayer'] = new AMap.TileLayer({
        zIndex: 10,
        getTileUrl: function(x, y, z) {
          return "http://bi.n3.cn/maptiler/1/" + z + "/" + x + "/" + y + ".png";
        }
      });

      self.mapLayers['HDVLayer'].setMap(self.mapObj);

      self.reqScreenData();

      // 将方法暴露到window中共模板拼接时调用

      window.closeProMapWindow = () => {
        self.mapObj.clearInfoWindow();
        self.area.hide();
      };

      // 监听地图zoom变化
      this.mapObj.on("zoomchange", () => {
        const zoom = this.mapObj.getZoom();
        if (zoom < config.middleZoom) {
          for (var item in self.pointers) {
            // 清空所有label
            self.pointers[item].setLabel({
              content: ""
            });
          }
        } else {
          for (var item in self.pointers) {
            // 清空所有label
            self.pointers[item].setLabel({
              //label默认蓝框白底左上角显示，样式className为：amap-marker-label
              offset: new AMap.Pixel(25, 5), //右侧
              zIndex: 99,
              content:
                "<div class='map-label'><span class='map-label-name'>" +
                self.allData.filter(b => b.serialno == item)[0].name +
                "</span></div>"
            });
          }
        }
      });
    },
    // 在地图上创建区域边界
    createAreaWall(name) {
      const self = this;
      let redPath = [];
      let projectArea = self.screenProject.area;
      if (projectArea && projectArea.length > 0) {
        projectArea.map(item =>
          redPath.push([Number(item.lng), Number(item.lat)])
        );
      }

      self.mapLayers['redPolygon'] = new AMap.Polygon({
        path: redPath,
        borderWeight: 5, // 线条宽度，默认为 1
        strokeColor: "#ff0000", // 线条颜色
        fillOpacity: 0,
        map: self.mapObj
      });
      self.mapObj.setFitView(self.mapLayers['redPolygon']);
    },
    changePage() {
      this.onePageVis = !this.onePageVis;
    },
    clickLink() {},
    // 创建marks
    createMarks() {
      const self = this;
      // 先清空所以点和动画点
      self.clearAllPointers();
      const allData = self.allData || [];
      // self.testArea = new AMap.Polygon({
      //   borderWeight: 1, // 线条宽度，默认为 1
      //   strokeColor: "#ddd", // 线条颜色
      //   map: self.mapObj,
      //   zIndex: 6
      // });
      allData.map((item, index) => {
        if (item.location.length < 2) {
          console.log("没有点位信息!");
        } else {
          // 创建一个 Marker 实例,并将点位信息保存在
          let marker = new AMap.Marker({
            position: item.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            offset: new AMap.Pixel(-10, -10),
            zIndex: 3,
            icon: require("../../assets/img/location/" + item.status + ".png") // 添加 Icon 图标 URL
          });
          // 如果项目正在实施中,则添加波动动画
          if (item.status && item.status === 1) {
            let markerContent =
              '<div class="ball-scale-multiple"><div></div><div></div><div></div></div>';
            let markerAnimate = new AMap.Marker({
              position: item.location, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              offset: new AMap.Pixel(-30, 20),
              zIndex: 2,
              content: markerContent,
              map: self.mapObj
            });
            self.animatePointers[item.serialno] = markerAnimate;
          }

          // 设置弹出框内容
          //构建自定义信息窗体
          function createInfoWindow(data) {
            let info =
              '<div class="el-popover el-popper map-window" style="position: relative; width:' +
              window.chartFontSize * 34 +
              'px;">' +
              // 头部
              '<div class="header">' +
              '<div class="title">' +
              data.shortTitle +
              "</div>" +
              '<button type="button" class="btn" onclick="closeMapWindow()"><i class="iconfont icon-close"></i></button>' +
              "</div>" +
              // 主要内容区域
              '<div class="main">' +
              "<table>" +
              "<tbody>" +
              '<tr><td rowspan="3"><img src="' +
              data.litpic +
              '" alt="data.title"/></td><td class="label">类型</td><td class="value">' +
              data.type +
              "</td></tr>" +
              '<tr><td class="label">面积</td><td class="value">' +
              data.levy_area +
              "㎡</td></tr>" +
              '<tr><td class="label">户数</td><td class="value">' +
              data.levy_number +
              "户</td></tr>" +
              '<tr><td class="label">地址</td><td class="value" colspan="2">' +
              data.address +
              "</td></tr>" +
              '<tr><td class="label">状态</td><td class="value" colspan="2">' +
              data.status +
              "</td></tr>" +
              '<tr><td class="value" colspan="3">' +
              data.abstract +
              "</td></tr>" +
              "</tbody>" +
              "</table>" +
              '<div class="detailBtn"><a href="javascript:void(0)" onclick="clickLink(this)" serialno="' +
              data.serialno +
              '">查看详情>></a></div>' +
              "</div>" +
              // button
              // 箭头
              '<div x-arrow class="popper__arrow top-arrow" style="left: ' +
              ((window.chartFontSize * 34) / 2 - 5) +
              'px;"></div>' +
              "</div>";
            return info;
          }

          AMap.event.addListener(marker, "click", async function(e) {
            self.mapObj.setFitView(this);
            self.showPop(item);
          });
          self.mapObj.add(marker);
          self.pointers[item.serialno] = marker; //保存点位信息
        }
      });
    },
    // 清除地图所有的点
    clearAllPointers() {
      const self = this;
      // 先清除所有点位
      for (let i in self.pointers) {
        // self.pointers[i].hide();
        self.mapObj.remove(self.pointers[i]);
      }
      for (let i in self.animatePointers) {
        // self.animatePointers[i].hide();
        self.mapObj.remove(self.animatePointers[i]);
      }
      self.pointers = {};
      self.animatePointers = {};
    },
    handlerConStatus(data) {
      this.contract_status = data;
    },
    // 返回首页
    gotoScreen() {
      this.$router.replace("/screen");
    },
    // 通过pop展示内容信息
    showPop(info) {
      const self = this;
      // self.testArea.hide();
      if (info.location && info.location.length < 1) {
        showMessage(self, "当前用户没有坐标信息!", "warning", "警告");
        return;
      }
      //构建自定义信息窗体
      function createInfoWindow(data) {
        let info =
          '<div class="el-popover el-popper map-window" style="position: relative; width:' +
          window.chartFontSize * 40 +
          'px;">' +
          // 头部
          '<div class="header">' +
          '<div class="title">' +
          data.name +
          "</div>" +
          '<button type="button" class="btn" onclick="closeProMapWindow()"><i class="iconfont icon-close"></i></button>' +
          "</div>" +
          // 主要内容区域
          '<div class="main">' +
          "<table>" +
          "<tbody>" +
          '<tr><td rowspan="3"><img src="' +
          data.litpic +
          '" alt="data.title"/></td><td class="label">状态</td><td class="value">' +
          data.status +
          "</td></tr>" +
          '<tr><td class="label">所属项目</td><td class="value">' +
          data.serialno +
          "</td></tr>" +
          '<tr><td class="label">编号</td><td class="value">' +
          data.serialno +
          "户</td></tr>" +
          '<tr><td class="label">地址</td><td class="value" colspan="2">' +
          data.houseaddress +
          "</td></tr>" +
          '<tr><td class="label">状态</td><td class="value" colspan="2">' +
          data.status +
          "</td></tr>" +
          // button
          "<tr class='pop-btns'><td colspan='3'>" +
          "<button type='button' class='map-button map-button-primary'>评估报告</button>" +
          "<button type='button' class='map-button map-button-primary'>协议</button>" +
          "<button type='button' class='map-button map-button-primary'>付款单</button>" +
          "<button type='button' class='map-button map-button-primary'>档案</button>" +
          "</td></tr>" +
          "</tbody>" +
          "</table>" +
          // "<div class='submit-box'>" +
          // "<button type='button' class='el-button el-button--default el-button--mini'>取消</button>" +
          // "<button type='button' class='el-button el-button--success el-button--mini'>同意签约</button>" +
          // "</div>" +
          // 箭头
          '<div x-arrow class="popper__arrow top-arrow" style="left: ' +
          ((window.chartFontSize * 40) / 2 - 5) +
          'px;"></div>' +
          "</div>";
        return info;
      }

      // 在allData中搜索当前点击点信息
      let clickObjData = self.allData.filter(
        item => item.serialno === (info.id || info.serialno)
      )[0];
      self.infoWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content: createInfoWindow(clickObjData),
        offset: new AMap.Pixel(-6, -25)
      });
      // 如果是通过地图点击的话就显示pop
      self.infoWindow.open(self.mapObj, info.location);
      self.mapObj.setFitView(self.pointers[info.serialno]);

      // 如果当前点击对象有面积信息则展示相应的面积信息
      if (clickObjData.area && clickObjData.area.length > 0) {
        let areaPath = clickObjData.area.map(item => [item.lng, item.lat]);
        // self.area.setPath(areaPath);
        // self.area.setOptions({
        //   fillColor: statusColor[clickObjData.status]
        // });
        // self.area.show();
      }
    },
    // 当搜索的内容栏被点击时
    handlerSearchItem(data) {
      this.showPop(data);
    },
    // 显示时间轴
    showTimeLine() {
      this.$refs.signStatus.dialogVisible = true;
    },
    // 切换legend选中状态
    handlerMapLegend(data) {
      const id = data.id;
      if (this.unselectedStatus.indexOf(id) != -1) {
        this.unselectedStatus.splice(this.unselectedStatus.indexOf(id), 1);
      } else {
        this.unselectedStatus.push(id);
      }
    },
    // 获取项目进度数据
    async getSignStatus() {
      const self = this;
      const data = await reqSignStatus({
        seqno: self.$router.history.current.query.seqno
      });
      if (data.code === 1) {
        this.signStatusData = data.data;
      }
    }
  },
  mounted() {
    const self = this;
    lazyAMapApiLoaderInstance.load().then(() => {
      self.initMap();
      self.getSignStatus();
    });
  },
  components: {
    PageOne,
    PageTwo,
    SearchContent,
    SignStatus,
    MapLegend,
    MapLayer
  }
};
</script>

<style lang='less' scoped>
@import "../../utils/theme.less";

.content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  // position: relative;
  display: flex;
  justify-content: center;
}
#map-content {
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}
.backBtn {
  font-size: 3rem;
  margin-right: 1vw;
  cursor: pointer;
  position: fixed;
  top: 2vw;
  left: 2vw;
  z-index: 99;
}
.header {
  position: absolute;
  top: 0;
  // left: 0;
  // height: 15%;
  // width: 100%;
  z-index: 6;
  color: #fff;
  overflow: hidden;
  .el-dropdown-link {
    color: #fff !important;
    font-size: 1.2rem !important;
    font-weight: 600 !important;
  }
  .el-dropdown-menu__item {
    font-size: 1.2rem !important;
    font-weight: 600 !important;
  }
  .title {
    display: block;
    font-size: 3rem;
    font-weight: 600;
    padding: 2vw 2.2vw 2vw;
    color: #fff;
  }
  .curStatus {
    font-size: 1.5rem;
    vertical-align: baseline;
    color: @primary;
    padding: 0;
    margin: 0;
    cursor: pointer;
    i {
      font-size: 1.5rem;
      color: @primary;
      margin-right: 0.3vw;
    }
  }
  .subTitle {
    font-size: 2.2rem;
    font-weight: 500;
    padding-bottom: 1vw;
  }
  .types {
    display: inline-block;
    span {
      padding: 0.5vw;
      cursor: pointer;
      font-size: 1.2rem;
      font-weight: 600;
      background: @bg;
      display: inline-block;
      margin-right: 0.5vw;
      border-radius: 0.5vw;
      i {
        font-size: 1.2rem;
        font-weight: 600;
      }
    }
    .active {
      color: @primary;
    }
  }
}

.btns {
  transition: right ease-out 0.6s, transform ease-out 0.6s;
  position: fixed;
  top: 50% - 2vw;
  right: 2vw;
  z-index: 10;
  .btn {
    // height: 4vw;
    // width: 4vw;
    font-size: 2rem;
    background: @primary;
  }
}

.btnHide {
  right: 94vw;
  transform: rotate(180deg);
}

.btnShow {
  // right: auto;
  right: 2vw;
  transform: rotate(0deg);
}
</style>
